import React from 'react';
import { observable, action, computed, toJS } from 'mobx';
import { Tools, Toast, Modal, ActionSheet, Bubble } from 'weaver-mobile';
import {MapPage} from 'weaver-mobile-page';
import * as publicFunc from '../util/public-func';
import {getOutSignSetting} from '../apis/sign';
import moment from 'moment';
import isEmpty from 'lodash/isEmpty';
import has from 'lodash/has';
const getLabel = Tools.getLabel;
const {alert} = Modal;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);

export default class BaseStore {
    //#region arguments
    toJS = toJS; 
    moment = moment;
    Toast = Toast;
    Bubble = Bubble;
    publicFunc = publicFunc;

    get em(){
        return window.em;
    }

    get ua(){
        return Tools.ua;
    }

    get browserType() {
        if(has(this.ua, 'browser'))
            return this.ua.browser.toLowerCase();
        return null;
    }

    get wrapProps(){
        if (isIPhone) {
            return {
                onTouchStart: e => e.preventDefault(),
            };
        }
        return {};
    }

    @observable spinning = false;
    //#endregion

    //#region showAlert
    @action showAlert = params => {
        const {title, message, okLabel, cancelLabel, onOk, onCancel, showCancel} = params;
        let btns = [{
            text: okLabel,
            onPress: onOk
        }];
        if(showCancel == null || !!showCancel){
            btns.unshift({
                text: cancelLabel,
                onPress: onCancel
            });
        }
        alert(title, message, btns);
    }
    //#endregion

    //#region showActionSheet
    @action showActionSheetWithOptions = params => {
        const {message, buttons: options} = params;
        ActionSheet.showActionSheetWithOptions({
            message,
            options,
            cancelButtonIndex: options.length - 1,
            'data-seed': 'logId',
            wrapProps: this.wrapProps
        });
    }
    //#endregion

    // //#region JEM
    // callJsApiFailed = message => new Promise((resolve, reject) => {
    //     Bubble.error(message);
    //     resolve({
    //         status: '-1',
    //         message
    //     })
    // })

    // checkJsApi = async (funcName, success) => new Promise((resolve, reject) => {
    //     let message = '';
    //     if(this.em == null)
    //         message = 'em not found';
    //     else{
    //         if(typeof(funcName) == 'string'){
    //             message = this.em.checkJsApi(funcName) ? '' : `${funcName} not found`;
    //         }else if(Array.isArray(funcName)){
    //             let arr = [];
    //             funcName.map(f => {
    //                 const s = this.em.checkJsApi(f) ? '' : f;
    //                 s != '' && arr.push(s);
    //             })
    //             arr.length > 0 && (message = `${arr.join(',')} not found`);
    //         }
    //     }
    //     const flag = (message == '');
    //     if(flag){
    //         if('getLocation' == funcName && this.em.checkJsApi('dingAuthFunc')){
    //             this.em.dingAuthFunc();
    //         }
    //         resolve(success());
    //     }else{
    //         resolve(this.callJsApiFailed(message));
    //     }
    // })
    // //#endregion

    // //#region 获取设备信息
    // getDeviceInfo = async () => {
    //     let funcName = this.browserType == 'dingtalk' ? 'getNetWorkInfo' : 'getClientInfo';
    //     const data = await this.checkJsApi(funcName, () => this.callDeviceInfo(funcName));
    //     return data;
    // }
    
    // @action callDeviceInfo = async funcName => {
    //     return new Promise((resolve, reject) => {
    //         this.em.ready(() => {
    //             this.em[funcName]({
    //                 success: res => {
    //                     resolve({status: '1', ...res});
    //                 },
    //                 fail: res => {
    //                     if(this.browserType == 'emobile'){
    //                         Bubble.error(<div onClick={() => Bubble.error(res.errMsg)}>{getLabel('504566','无法获取设备信息')}</div>);
    //                     }
    //                     resolve({status: '-1'});
    //                 }
    //             })
    //         })
    //     })
    // }
    // //#endregion

    // //#region 获取定信息
    // @action getLocation = async onLocationChangedHandle => {
    //     const data = await this.checkJsApi('getLocation', () => this.callGetLocation(onLocationChangedHandle));
    //     if(data.status == '-1'){
    //         //test
    //         Object.assign(data, {
    //             address: '联航路1188号',
    //             longitude: 121.52646,
    //             latitude: 31.08013,
    //             status: '1'
    //         });
    //     }else{
    //         if(isEmpty(data.address)){
    //             const regeoData = await this.regeo(data);
    //             Object.assign(data, regeoData);
    //         }
    //     }
    //     return data;
    // }

    // @action callGetLocation = async onLocationChangedHandle => new Promise((resolve, reject) => {
    //     const params = {};
    //     if(this.isAmap){
    //         Object.assign(params, {type: 'gcj02'});
    //     }else if(this.isGoogleMap){
    //         Object.assign(params, {
    //             locationType: 'Google',
    //             ios_googleMap_key: this.googleMapKey,
    //             and_googleMap_key: this.googleMapKey
    //         })
    //     }
    //     this.em.ready(() => {
    //         this.em.getLocation({
    //             ...params,
    //             success: res => {
    //                 resolve({status: '1', ...res});
    //             },
    //             onLocationChanged: res => {
    //                 if(typeof(res) === 'string')
    //                     res = JSON.parse(res);
    //                 onLocationChangedHandle && onLocationChangedHandle({status: '1', ...res});
    //             },
    //             fail: res => {
    //                 Bubble.error(<div onClick={() => Bubble.error(res.errMsg)}>{getLabel('504565','无法获取定位信息')}</div>);
    //                 resolve({status: '-1'});
    //             }
    //         })
    //     })
    // })
    // //#endregion

    //#region format request params
    // formatUrl = params => {
    //     params = Object.values(params).reduce((a,b,i) => `${a}${Object.keys(params)[i]}=${b}&`, '?');
    //     return params.substring(0, params.length - 1);
    // }
    //#endregion

    //#region 地图相关
    // @observable mapStore = new MapPage.Store();

    // @observable _mapInited = false;
    // @computed get mapInited(){return this._mapInited}
    // set mapInited(v){this._mapInited = v}

    // setMapType = type => this.mapStore.setMapType(type);

    // get defaultMapParams(){
    //     return this.mapStore.getDefaultMapParams();
    // }

    // @computed get currentMapType(){
    //     return this.mapStore.mapType || this.defaultMapParams.defaultMap;
    // }

    // @computed get isAmap(){
    //     return this.currentMapType.toLowerCase() === 'gaode';
    // }

    // @computed get isGoogleMap(){
    //     return this.currentMapType.toLowerCase() === 'google';
    // }

    // @computed get googleMapStore(){
    //     return this.mapStore.googleMapStore;
    // }

    // get amapWebServiceKey(){
    //     try{
    //         return this.defaultMapParams.gaodeMapWebServiceKey;
    //     }catch(e){
    //         return '';
    //     }
    // }

    // get googleMapKey(){
    //     try{
    //         return this.defaultMapParams.googleMapKey;
    //     }catch(e){
    //         return '';
    //     }
    // }
    //#endregion

    @action debounce = callback => {
        if(this.timeout){
            clearTimeout(this.timeout);
            this.timeout = null;
        }
        this.timeout = setTimeout(() => {
            callback && callback();
        }, 50);
    }

    @action reduce = arr => {
        let sequence = Promise.resolve();
        arr.map(item => {
            sequence = sequence.then(item);
        });
        return sequence;
    }

    getOsInfo = async () => {
        let data = await Tools.callApi({url: '/api/system/info/getOSinfo', method: 'GET'});
        if(data.status){
            data.mapParams.ableToSwitchMap = "true";
            localStorage.setItem('getOsInfo', JSON.stringify(data));
        }
    }
}